package com.dofast.bt.util;

import android.annotation.TargetApi;
import android.content.ContentUris;
import android.content.Context;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.BitmapFactory.Options;
import android.graphics.Canvas;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.media.ExifInterface;
import android.media.ThumbnailUtils;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.provider.DocumentsContract;
import android.provider.MediaStore;
import android.view.View;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

public class BitmapUtil {

	/**
	 * 将Bitmap放入缓存�?
	 * 
	 * @Title: saveDrawableToCache
	 * @param bitmap
	 * @param filePath
	 * @return
	 * @return void
	 * @date 2012-12-14 上午9:27:38
	 */
	public static void saveDrawableToCache(Bitmap bitmap, String filePath) {

		try {
			File file = new File(filePath);
			if(!file.exists()) {
				file.getParentFile().mkdirs();
				file.createNewFile();
			}

			OutputStream outStream = new FileOutputStream(file);
			bitmap.compress(Bitmap.CompressFormat.JPEG, 100, outStream);
			outStream.flush();
			outStream.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	/**
	 * 读取本地资源的图片
	 *
	 * @param context
	 * @param resId
	 * @return
	 */
	public static Bitmap ReadBitmapById(Context context, int resId) {
		Options opt = new Options();
		opt.inPreferredConfig = Bitmap.Config.RGB_565;
		opt.inPurgeable = true;
		opt.inInputShareable = true;
		// 获取资源图片
		InputStream is = context.getResources().openRawResource(resId);
		return BitmapFactory.decodeStream(is, null, opt);
	}
	public static Bitmap getLayoutBitmap(View view) {
		view.invalidate();
		view.setDrawingCacheEnabled(true);
		view.buildDrawingCache();
		Bitmap bitmap = view.getDrawingCache();
		// final String cropPath = new
		// FileUtils(PublishBookActivity.this).makeAppDir()+ "/" + "temp.jpg";
		// BitmapUtil.saveDrawableToCache(bitmap, cropPath);
		// croppedImage.recycle();
		return bitmap;
	}

	public static String getLayoutBitmap(View view, Context mContext) {
		view.invalidate();
		view.setDrawingCacheEnabled(true);
		view.buildDrawingCache();
		Bitmap bitmap = view.getDrawingCache();
		final String cropPath = new FileUtils(mContext).makeAppDir() + "/"
				+ "temp.jpg";
		saveDrawableToCache(bitmap, cropPath);
		view.destroyDrawingCache();
		return cropPath;
	}

	public static Bitmap adjustPhotoRotation(Bitmap bm,
											 final int orientationDegree) {

		Matrix m = new Matrix();
		m.setRotate(orientationDegree, (float) bm.getWidth() / 2,
				(float) bm.getHeight() / 2);
		float targetX, targetY;
		if (orientationDegree == 90) {
			targetX = bm.getHeight();
			targetY = 0;
		} else {
			targetX = bm.getHeight();
			targetY = bm.getWidth();
		}

		final float[] values = new float[9];
		m.getValues(values);

		float x1 = values[Matrix.MTRANS_X];
		float y1 = values[Matrix.MTRANS_Y];

		m.postTranslate(targetX - x1, targetY - y1);

		try {
			Bitmap bm1 = Bitmap.createBitmap(bm.getHeight(), bm.getWidth(),
					Bitmap.Config.ARGB_8888);
			Paint paint = new Paint();
			Canvas canvas = new Canvas(bm1);
			canvas.drawBitmap(bm, m, paint);

			return bm1;

		} catch (Error error) {
		} catch (Exception e) {
		}

		return null;
	}

	/**
	 * 压缩图片
	 * 
	 * @param context
	 * @param resId
	 * @param width
	 * @param height
	 * @return
	 */
	public static Bitmap compressImage(Context context, int resId, int width,
									   int height) {
		Options options = new Options();
		options.inJustDecodeBounds = true;

		BitmapFactory.decodeResource(context.getResources(), resId, options);

		options.inJustDecodeBounds = false;
		float w = options.outWidth;
		float h = options.outHeight;

		// 缩放比�?由于是固定比例缩放，只用高或者宽其中�?��数据进行计算即可
		int be = 1;// be=1表示不缩�?
		if (w >= h) {// 如果宽度大的话根据宽度固定大小缩�?

			be = (int) (w / width);

		} else if (w < h) {// 如果高度高的话根据宽度固定大小缩�?
			be = (int) (h / height);
		}
		if (be <= 0) {
			be = 1;
		}

		if (be != 1) {
			options.inSampleSize = be;// 设置缩放比例
			return BitmapFactory.decodeResource(context.getResources(), resId,
					options);
		} else {
			return null;
		}
	}

	/**
	 * 压缩图片
	 * 
	 * @param context
	 * @param resId
	 *            缩放尺寸
	 * @return
	 */
	public static Bitmap forceCompressImageSize(Context context, int resId,
												int width, int height) {

		Options options = new Options();
		options.inJustDecodeBounds = true;
		BitmapFactory.decodeResource(context.getResources(), resId, options);

		if (width > options.outWidth) {
			width = options.outWidth;
			height = options.outHeight;
		}

		Bitmap bitmap = BitmapFactory.decodeResource(context.getResources(),
				resId);
		Bitmap result = null;
		if (bitmap != null) {

			result = ThumbnailUtils.extractThumbnail(bitmap, width, height);

			if (result != bitmap) {
				bitmap.recycle();
			}
		}

		return result;
	}

	public static int getBitmapDegree(String path) {
		int degree = 0;
		try {
			// 从指定路径下读取图片，并获取其EXIF信息
			ExifInterface exifInterface = new ExifInterface(path);
			// 获取图片的旋转信�?
			int orientation = exifInterface.getAttributeInt(
					ExifInterface.TAG_ORIENTATION,
					ExifInterface.ORIENTATION_NORMAL);
			switch (orientation) {
			case ExifInterface.ORIENTATION_ROTATE_90:
				degree = 90;
				break;
			case ExifInterface.ORIENTATION_ROTATE_180:
				degree = 180;
				break;
			case ExifInterface.ORIENTATION_ROTATE_270:
				degree = 270;
				break;
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
		return degree;
	}

	/**
	 * bm自动被回�?
	 * 
	 * @param bm
	 * @param degree
	 * @return
	 */
	public static Bitmap rotateBitmapByDegree(Bitmap bm, int degree) {
		Bitmap returnBm = null;

		// 根据旋转角度，生成旋转矩�?
		Matrix matrix = new Matrix();
		matrix.postRotate(degree);
		try {
			// 将原始图片按照旋转矩阵进行旋转，并得到新的图�?
			returnBm = Bitmap.createBitmap(bm, 0, 0, bm.getWidth(),
					bm.getHeight(), matrix, true);
		} catch (Error e) {

			if (returnBm != null) {
				try {
					returnBm.recycle();
				} catch (Exception ee) {
				}
				returnBm = null;
			}

		} catch (Exception e) {
			if (returnBm != null) {
				try {
					returnBm.recycle();
				} catch (Exception ee) {
				}
				returnBm = null;
			}
		}
		if (returnBm == null) {
			returnBm = bm;
		}
		if (bm != returnBm) {
			bm.recycle();
		}
		return returnBm;
	}

	@TargetApi(Build.VERSION_CODES.KITKAT)
	public static String getPath(final Context context, final Uri uri) {

		final boolean isKitKat = Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT;

		// DocumentProvider
		if (isKitKat && DocumentsContract.isDocumentUri(context, uri)) {
			// ExternalStorageProvider
			if (isExternalStorageDocument(uri)) {
				final String docId = DocumentsContract.getDocumentId(uri);
				final String[] split = docId.split(":");
				final String type = split[0];

				if ("primary".equalsIgnoreCase(type)) {
					return Environment.getExternalStorageDirectory() + "/"
							+ split[1];
				}

			}
			// DownloadsProvider
			else if (isDownloadsDocument(uri)) {
				final String id = DocumentsContract.getDocumentId(uri);
				final Uri contentUri = ContentUris.withAppendedId(
						Uri.parse("content://downloads/public_downloads"),
						Long.valueOf(id));

				return getDataColumn(context, contentUri, null, null);
			}
			// MediaProvider
			else if (isMediaDocument(uri)) {
				final String docId = DocumentsContract.getDocumentId(uri);
				final String[] split = docId.split(":");
				final String type = split[0];

				Uri contentUri = null;
				if ("image".equals(type)) {
					contentUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
				} else if ("video".equals(type)) {
					contentUri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI;
				} else if ("audio".equals(type)) {
					contentUri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
				}

				final String selection = "_id=?";
				final String[] selectionArgs = new String[] { split[1] };

				return getDataColumn(context, contentUri, selection,
						selectionArgs);
			}
		}
		// MediaStore (and general)
		else if ("content".equalsIgnoreCase(uri.getScheme())) {
			// Return the remote address
			if (isGooglePhotosUri(uri))
				return uri.getLastPathSegment();

			return getDataColumn(context, uri, null, null);
		}
		// File
		else if ("file".equalsIgnoreCase(uri.getScheme())) {
			return uri.getPath();
		}

		return null;
	}

	public static String getDataColumn(Context context, Uri uri,
									   String selection, String[] selectionArgs) {

		Cursor cursor = null;
		final String column = "_data";
		final String[] projection = { column };

		try {
			cursor = context.getContentResolver().query(uri, projection,
					selection, selectionArgs, null);
			if (cursor != null && cursor.moveToFirst()) {
				final int index = cursor.getColumnIndexOrThrow(column);
				return cursor.getString(index);
			}
		} finally {
			if (cursor != null)
				cursor.close();
		}
		return null;
	}

	public static boolean isExternalStorageDocument(Uri uri) {
		return "com.android.externalstorage.documents".equals(uri
				.getAuthority());
	}

	/**
	 * @param uri
	 *            The Uri to check.
	 * @return Whether the Uri authority is DownloadsProvider.
	 */
	public static boolean isDownloadsDocument(Uri uri) {
		return "com.android.providers.downloads.documents".equals(uri
				.getAuthority());
	}

	/**
	 * @param uri
	 *            The Uri to check.
	 * @return Whether the Uri authority is MediaProvider.
	 */
	public static boolean isMediaDocument(Uri uri) {
		return "com.android.providers.media.documents".equals(uri
				.getAuthority());
	}

	/**
	 * @param uri
	 *            The Uri to check.
	 * @return Whether the Uri authority is Google Photos.
	 */
	public static boolean isGooglePhotosUri(Uri uri) {
		return "com.google.android.apps.photos.content".equals(uri
				.getAuthority());
	}
}
